package com.headwind.listener;

import com.headwind.entity.HwUser;
import com.headwind.service.HwUserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.List;

/**
 * @author : Headwind
 * @version : 1.0
 * @date : Created in 2020/8/15
 * @description : 用户监视器
 */
@WebListener
public class HwUserListener implements ServletContextListener {
    @Autowired
    private HwUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    private static final String ALL_USER = "ALL_USER_LIST";
    /**
     * 添加Log4j2容器
     */
    Logger log = LogManager.getLogger(this.getClass());

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //查询所有用户信息
        List<HwUser> userList = userService.findAllUser();
        //清除缓存的用户信息
        redisTemplate.delete(ALL_USER);
        //将数据缓存到Redis缓存中
        redisTemplate.opsForList().leftPushAll(ALL_USER, userList);
        log.info("Servlet Context上下文初始化。");
        log.info("缓存中当前用户数有：" + userList.size() + " 人。");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        log.info("Servlet Context上下文销毁。");
    }
}
